package com.jxin.mall.core.proxy;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 捕捉异常,让代码不会因为函数内抛异常而终止
 * @author  蔡佳新
 * @version 1.0
 * @since   jdk 1.8
 */
@Slf4j
public class CatchThrowsProxy  implements InvocationHandler {
    private Object target;

    public Object bind(Object target) {
        this.target = target;
        return Proxy.newProxyInstance(CatchThrowsProxy.class.getClassLoader(),
                target.getClass().getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args){

        Object result = null;
        try {
            result = method.invoke(target, args);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }
}
